local wb = Game:addState("wb")

function wb:enteredState()
	print("entered world builder")

	self:init_gui()	



end

function wb:update(dt)
	
	-- check if tile has been returned from thread
	local ntc = love.thread.getChannel("new_tile")
	if ntc:peek() then
		local nt = ntc:pop()		
		self.world:add_tile(nt)
		-- show finish and save button after last tile
		if nt.y == self.world.data.stats.lat 
			and nt.x == self.world.data.stats.long
			and nt.z == self.world.data.stats.ele then
			self.finished_button:SetVisible(true)
			self.progress_bar:SetVisible(false)
			self.save_button:SetVisible(true)
		end
		--print(nt.z)
		local pz = nt.z/self.world.data.stats.ele
		pz = math.floor(pz*100)
		--print(pz .. "%")
		self:progress_gui("Receiving Tiles .. " .. pz .. "%")
	end
	

	--local gfc = love.thread.getChannel("world_gen_finished")
	--if gfc:peek() then
	--	gfc:pop()
	--	self.finished_button:SetVisible(true)
	--end

	-- check progress of world builder, display results
	local wbpc = love.thread.getChannel("wg_progress")
	if wbpc:peek() then
		local wbp = wbpc:pop()
		if self.progress_gui then
			self:progress_gui(wbp)
		end
	end
end

function wb:keypressed(key, isRepeat)
end

function wb:keyreleased(key)
end

function wb:mousepressed(x, y, button)
end

function wb:mousereleased(x, y, button)
end

function wb:draw()
end

function wb:init_gui()
	-- main frame
	self.mf = loveframes.Create("frame")
	local mf = self.mf
	mf:SetName("World Options")
	mf:SetSize(435, 600)
	mf:ShowCloseButton(false)
	mf:Center()

	-- generate button
	local gb = loveframes.Create("button", mf)
	gb:CenterX()
	gb:SetY(570)
	gb:SetText("Generate")

	-- world sliders
	--left side
	gb.lat = game.gu:labeledSlider("World Latitude", 5, 30, 100, 1, 5, 
		{"Very Small", "Small", "Medium", "Large", "Extra Large"}, mf)
	gb.long = game.gu:labeledSlider("World Longitude", 5, 110, 100, 1, 5,
		{"Very Small", "Small", "Medium", "Large", "Extra Large"}, mf)
	gb.ele = game.gu:labeledSlider("World Elevation", 5, 190, 100, 1, 5,
	 	{"Very Small", "Small", "Medium", "Large", "Extra Large"}, mf)
	gb.temp = game.gu:labeledSlider("World Temperature", 5, 270, 100, 1, 5,
	 	{"Cold", "Cool", "Moderate", "Hot", "Scorching"}, mf)
	gb.sea = game.gu:labeledSlider("Sea Level", 5, 350, 100, 1, 5,
	 	{"Very Low", "Low Tide", "Average", "High Tide", "Surfs Up"}, mf)
	--right side
	gb.ene = game.gu:labeledSlider("Enemies", 220, 30, 100, 1, 5,
	 	{"Very Few", "Few", "Average", "Many", "Abundant"}, mf)
	gb.fri = game.gu:labeledSlider("Friendlies", 220, 110, 100, 1, 5,
	 	{"Very Few", "Few", "Average", "Many", "Abundant"}, mf)
	gb.res = game.gu:labeledSlider("Resources", 220, 190, 100, 1, 5,
	 	{"Very Few", "Few", "Average", "Many", "Abundant"}, mf)
	gb.feat = game.gu:labeledSlider("Features", 220, 270, 100, 1, 5,
	 	{"Very Few", "Few", "Average", "Many", "Abundant"}, mf)

	-- generate button callback, creates world	
	gb.OnClick = function(object)

		
		local lat, long, ele, temp, ene, fri, res, feat, sea = self:translate_sliders(
			object.lat:GetValue(), object.long:GetValue(),
			object.ele:GetValue(), object.temp:GetValue(), 
			object.ene:GetValue(), object.fri:GetValue(), 
			object.res:GetValue(), object.feat:GetValue(),
			object.sea:GetValue())
		game.world = World:new(lat, long, ele, temp, ene, fri, res, feat, sea)
		object:SetVisible(false)
		game.progress_bar:SetVisible(true)
	end

	-- progress of generation text
	self.progress_text = loveframes.Create("text", mf)
	local pt = self.progress_text
	--pt:SetShadowColor(200, 200, 200, 255)
	pt:CenterX()
	pt:SetY(555)
	pt:SetDefaultColor(0,0,0,255)
	pt:SetText("0%")

	-- progress of gen bar
	self.progress_bar = loveframes.Create("progressbar", mf)
	local pb = self.progress_bar
	pb:CenterX()
	pb:SetY(570)
	pb:SetMinMax(0, 100)
	pb:SetVisible(false)

	-- finished button
	self.finished_button = loveframes.Create("button", mf)
	local fb = self.finished_button
	fb:CenterX()
	fb:SetY(570)
	fb:SetText("View World")
	fb:SetVisible(false)
	fb.OnClick = function()
		game:gotoState("ViewWorld")
	end
	

	-- save button
	self.save_button = loveframes.Create("button", mf)
	local sb = self.save_button
	sb:SetX(30)
	sb:SetY(570)
	sb:SetText("Save World")
	sb:SetVisible(false)
	sb.OnClick = function()
		self.save_text:SetVisible(true)
	end

	-- save dialog
	self.save_text = loveframes.Create("textinput", mf)
	local st = self.save_text
	st:Center()
	st:SetVisible(false)
	st.OnEnter = function(object, text)
		if text then
			self.save_name = text .. ".sav"
			local t = self.save_name
			print("saving .. " .. t)
			--if love.filesystem.isFile(t) then

			--else
				local file = love.filesystem.newFile(t) 
				print('file made')
				local td = JSON:encode(game.world.data)
				print('file encoded')
				file:open('w')
				local ok = file:write(td)
				if not ok then
					print('file not written')
				else
					print('file wrote')
				end
				file:flush()
				file:close()
				print('file closed')
			--end
			object:SetVisible(false)
		end
		
	end	

end

function wb:progress_gui(progress)

	local pt = self.progress_text
	local s = progress
	pt:SetText(s)
	pt:CenterX()
	local val = progress:match('%d+')
	val = tonumber(val)
	if val then
		local pb = self.progress_bar
		pb:SetValue(val)
	end

end

-- reads sliders and returns their values
function wb:translate_sliders(lat, long, ele, temp, ene, fri, res, feat, sea)

	local size_opts = {
		[1] = function() return 32 end,
		[2] = function() return 64 end,
		[3] = function() return 128 end,
		[4] = function() return 256 end,
		[5] = function() return 512 end,
	}
	local nlat = size_opts[lat]()
	local nlong = size_opts[long]()
	local nele = size_opts[ele]()

	local temp_opts = {
		[1] = function() return 30 end,
		[2] = function() return 50 end,
		[3] = function() return 70 end,
		[4] = function() return 90 end,
		[5] = function() return 110 end,
	}
	local ntemp = temp_opts[temp]()
	
	local maxP = 5
	local nene = ene/maxP
	local nfri = fri/maxP
	local nres = res/maxP
	local nfeat = feat/maxP

	local sea_opts = {
		[1] = function() return math.floor(nele*0.1) end,
		[2] = function() return math.floor(nele*0.3) end,
		[3] = function() return math.floor(nele*0.5) end,
		[4] = function() return math.floor(nele*0.7) end,
		[5] = function() return math.floor(nele*0.9) end,
	}
	local nsea = sea_opts[sea]()

	return nlat, nlong, nele, ntemp, nene, nfri, nres, nfeat, nsea
end

function wb:exitedState()
	print("exited world builder")
	loveframes.util.RemoveAll()
end